(function() {
  var findNext, randIndex, searchUser,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  randIndex = function(min, max, cnt, except) {
    var i, newRand, ret;
    if (except == null) {
      except = [];
    }
    ret = [];
    i = 999999;
    while (ret.length < cnt && max - min > 0 && i-- > 0) {
      newRand = Math.floor(Math.random() * (max - min + 1)) + min;
      if (__indexOf.call(ret, newRand) < 0 && __indexOf.call(except, newRand) < 0) {
        ret.push(newRand);
      }
    }
    ret.sort();
    return ret;
  };

  findNext = true;

  searchUser = function(response, again) {
    var $allBox, clickImg, currentPage, endExistNum, endItemIndex, endNeedNum, i, isTmall, itemBox, nextPageDom, preExistNum, preItemIndex, preNeedNum, sellerBoxIndex, time, v;
    if (again == null) {
      again = true;
    }
    $allBox = $('.tb-content .item-box');
    i = 0;
    sellerBoxIndex = -1;
    itemBox = [];
    isTmall = function(box) {
      return $('.icon-service-tianmao', box).size() > 0;
    };
    $allBox.each(function() {
      if ($('.seller a', this).html() === response.sellername) {
        if (isTmall(this)) {
          alert('被刷店是天猫，请手动刷单');
          return false;
        }
        if (sellerBoxIndex >= 0) {
          return true;
        }
        sellerBoxIndex = i;
      }
      if (isTmall(this)) {
        return true;
      }
      return itemBox[i++] = this;
    });
    if (sellerBoxIndex < 0) {
      if (again) {
        return setTimeout(function() {
          return searchUser(response, false);
        }, 10000);
      } else {
        currentPage = $('.pagination span.page-cur').html();
        nextPageDom = $('.page-siblings .page-next')[0];
        if ((0 < currentPage && currentPage < 4) && nextPageDom && findNext) {
          return simulateClick(nextPageDom);
        } else {
          return alert('前4页都没有找到');
        }
      }
    } else {
      preItemIndex = [];
      preNeedNum = response.enterNo - 1;
      preExistNum = sellerBoxIndex;
      endItemIndex = [];
      endNeedNum = response.compare - response.enterNo + 1;
      endExistNum = itemBox.length - sellerBoxIndex - 1;
      if (preNeedNum <= preExistNum) {
        preItemIndex = randIndex(0, sellerBoxIndex - 1, preNeedNum);
        if (endNeedNum <= endExistNum) {
          endItemIndex = randIndex(sellerBoxIndex + 1, itemBox.length - 1, endNeedNum);
        } else {
          endItemIndex = (function() {
            var _i, _ref, _ref1, _results;
            _results = [];
            for (v = _i = _ref = sellerBoxIndex + 1, _ref1 = itemBox.length - 1; _ref <= _ref1 ? _i <= _ref1 : _i >= _ref1; v = _ref <= _ref1 ? ++_i : --_i) {
              _results.push(v);
            }
            return _results;
          })();
          endItemIndex = endItemIndex.concat(randIndex(0, sellerBoxIndex - 1, endNeedNum - endExistNum, preItemIndex));
        }
      } else {
        preItemIndex = randIndex(0, preNeedNum, preNeedNum, [sellerBoxIndex]);
        endItemIndex = randIndex(preNeedNum + 1, itemBox.length - 1, endNeedNum);
      }
      time = 0;
      clickImg = function(indexes, second) {
        var dom, index, _fn, _i, _len, _results;
        _fn = function(dom, time) {
          return setTimeout(function() {
            var img;
            img = $('.pic-box a img', dom);
            return simulateClick(img[0], {
              ctrl: true
            });
          }, time);
        };
        _results = [];
        for (_i = 0, _len = indexes.length; _i < _len; _i++) {
          index = indexes[_i];
          dom = itemBox[index];
          _fn(dom, time);
          console.debug("time is " + time);
          time += second;
          _results.push(console.debug("time end is " + time));
        }
        return _results;
      };
      clickImg(preItemIndex, response.compareTime * 65000);
      clickImg([sellerBoxIndex], response.mainWatchTime * 65000);
      clickImg(endItemIndex, response.compareTime * 65000);
      setTimeout(function() {
        var startViewOtherMsg;
        console.debug('start view other goods', new Date().toLocaleTimeString());
        startViewOtherMsg = {
          dispatch: {
            startViewOther: 1
          }
        };
        return chrome.extension.sendRequest(startViewOtherMsg, function(response) {
          return console.log(response);
        });
      }, time);
      return setTimeout(function() {
        var compeletMsg;
        console.debug('order now', new Date().toLocaleTimeString());
        compeletMsg = {
          dispatch: {
            firstViewComplete: 1
          }
        };
        return chrome.extension.sendRequest(compeletMsg, function(response) {
          return console.log(response);
        });
      }, time + (response.otherGoodsNum * response.otherGoodsTime + response.indexWatchTime) * 65 * 1000);
    }
  };

  chrome.extension.sendRequest({
    sellername: 1,
    compare: 1,
    enterNo: 1,
    compareTime: 1,
    otherGoodsTime: 1,
    mainWatchTime: 1,
    otherGoodsNum: 1,
    otherGoodsNum: 1,
    indexWatchTime: 1
  }, function(response) {
    if (response && response.buy && response.buy.sellername) {
      document.body.scrollTop += 1600;
      setTimeout(function() {
        return searchUser(response.buy);
      }, 5000);
      return $(document).keyup(function(e) {
        if (78 === e.keyCode && e.altKey) {
          if (!findNext) {
            searchUser(response.buy, false);
          }
          return findNext = !findNext;
        }
      });
    }
  });

}).call(this);
